<template>
  <div class="box-fillreport">
    <!-- :default-selected-keys="defaultSelectedKeys" -->
    <div class="tree-content">
      <el-tree
        ref="fillreportTreeRef"
        :default-expanded-keys="defaultExpandedKeys"
        :current-node-key="defaultCurrentNodeKey"
        :load="loadNode"
        lazy
        node-key="id"
        highlight-current
        :render-after-expand="false"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <template #default="{ node }">
          <span class="node-content" :title="node.label">
            {{ node.label }}
          </span>
        </template>
      </el-tree>
    </div>
    <div class="box-controller">
      <div class="box-search">
        <div class="box-search-left">
          <el-form :inline="true" :model="formParam" style="width: 100%">
            <el-row :gutter="20">
              <!-- 指标名称 -->
              <el-col :span="6">
                <el-form-item label="指标名称:">
                  <el-input v-model="formParam.label" placeholder="请输入角色名称" clearable />
                </el-form-item>
              </el-col>

              <!-- 状态选择 -->
              <el-col :span="4">
                <el-form-item label="状态:">
                  <el-select v-model="formParam.status" placeholder="请选择状态" clearable>
                    <el-option
                      v-for="(item, index) of auditStatusList"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- 预警指标 -->
              <el-col :span="4">
                <el-form-item label="预警指标:">
                  <el-select
                    v-model="formParam.isAlertIndicator"
                    placeholder="请选择状态"
                    clearable
                    style="width: 100%"
                  >
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- 更新日期 -->
              <el-col :span="6">
                <el-form-item label="更新日期:">
                  <el-date-picker
                    v-model="tempDateRange"
                    type="daterange"
                    range-separator="-"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item class="form-item-responsive">
                  <el-button type="primary" class="zdy-btn" @click="searchWay">查询</el-button>
                  <el-button class="zdy-btn" @click="resetForm">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- <div class="box-search-right">
          <el-button type="primary" class="zdy-btn" @click="searchWay">查询</el-button>
          <el-button class="zdy-btn" @click="resetForm">重置</el-button>
        </div> -->
      </div>
      <div class="controller-page">
        <div class="card-table">
          <div class="card-total-txt">
            <span>共搜索到{{ total }}条数据</span>
          </div>
          <div class="btn-group-tool">
            <el-button type="primary" plain @click="batchApplyFor">批量审批申请</el-button>
            <el-button type="primary" plain @click="batchHistory">审批申请历史</el-button>
          </div>

          <div class="btn-group-notice">
            <el-icon class="icon"><InfoFilled /></el-icon>
            <span class="txt">已选择</span>
            <span class="num">{{ multipleSelection.length }}</span>
            <span class="txt">项</span>
          </div>

          <div class="table-list">
            <el-table
              ref="multipleTableRef"
              :data="dataList"
              row-key="id"
              style="width: 100%"
              height="100%"
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" :selectable="selectable" width="55" />
              <el-table-column prop="indicator" align="left" label="指标名称" min-width="200"> </el-table-column>

              <el-table-column prop="status" align="left" label="状态" min-width="140">
                <template #default="scope">
                  <div class="statusBox">
                    <span class="point" :class="getStatusColor(scope.row.status)"></span>
                    <span>
                      {{ getStatusLabel(scope.row.status) }}
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="dataType" align="left" label="数据源" width="120">
                <template #default="scope">
                  {{ scope.row.dataType === "1" ? "填报" : "链接" }}
                </template>
              </el-table-column>
              <el-table-column prop="currentValue" align="left" label="现值" min-width="100" />
              <el-table-column prop="targetValue" align="left" label="目标值" min-width="100" />

              <el-table-column prop="isAlertIndicator" align="left" label="预警指标" width="120">
                <template #default="scope">
                  {{ scope.row.isAlertIndicator === "0" ? "否" : "是" }}
                </template>
              </el-table-column>

              <el-table-column prop="updatedAt" align="left" label="更新时间" min-width="180"> </el-table-column>

              <el-table-column prop="newIndicator" align="left" label="指标名称修改" width="200">
                <template #default="scope">
                  <el-input v-model="scope.row.newIndicator" placeholder="请输入" clearable />
                </template>
              </el-table-column>

              <el-table-column prop="newDataType" align="left" label="数据源修改" width="120">
                <template #default="scope">
                  <el-select v-model="scope.row.newDataType" placeholder="数据源" clearable>
                    <el-option label="填报" value="0" />
                    <el-option label="链接" value="1" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column prop="newCurrentValue" align="left" label="指标修改" width="130">
                <template #default="scope">
                  <el-input v-model="scope.row.newCurrentValue" placeholder="请输入" clearable />
                </template>
              </el-table-column>
              <el-table-column prop="newTargetValue" align="left" label="目标修改" width="130">
                <template #default="scope">
                  <el-input v-model="scope.row.newTargetValue" placeholder="请输入" clearable />
                </template>
              </el-table-column>

              <el-table-column prop="newIsAlertIndicator" align="left" label="预警指标修改" width="130">
                <template #default="scope">
                  <el-select v-model="scope.row.newIsAlertIndicator" placeholder="预警指标" clearable>
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column fixed="right" align="left" label="操作" width="220">
                <template #default="{ row }">
                  <el-button link type="primary" size="small" @click="saveHandle(row)" :disabled="row.status === '2'">
                    保存
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button link type="primary" size="small" @click="auditHandle(row)" :disabled="row.status !== '1'">
                    报批
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button link type="primary" size="small" @click="historyHandle(row)"> 历史数据 </el-button>
                  <el-divider direction="vertical" />
                  <el-button link type="primary" size="small" @click="previewHandle(row)"> 预览 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="card-pagination">
            <el-pagination
              :small="true"
              v-model:current-page="formParam.pageNum"
              v-model:page-size="formParam.pageSize"
              layout="total, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <historyDrawerCom
      :isDrawer="showHistoryDrawer"
      :id="showHistoryDrawerId"
      @close="showHistoryDrawer = false"
    ></historyDrawerCom>

    <auditSituationDialog
      ref="auditSituationRef"
      v-model:visible="auditSituationVisible"
      :title="auditSituationTitle"
      :dialogType="auditSituationType"
      :rowData="auditSituationRow"
      @updateList="getFillreportListFunc"
    ></auditSituationDialog>

    <historyDialog ref="historyDialogRef" v-model:visible="historyDialogVisible" :title="historyDialogTitle">
    </historyDialog>
  </div>
</template>

<script setup>
import { onMounted, ref, watchEffect, reactive, computed, nextTick, onBeforeMount } from "vue"
import { Search, UserFilled, ArrowDown, Edit, Check } from "@element-plus/icons-vue"

import historyDrawerCom from "./components/historyDrawerCom.vue"

import auditSituationDialog from "./components/auditSituationDialog.vue"
import historyDialog from "./components/historyDialog.vue"

import { CountTo } from "vue3-count-to"
import dayjs from "dayjs"

import { ElMessage, ElMessageBox } from "element-plus"
import { applyMetrics, nodeLoading, nodePage, saveAsDraft, treeWithLevels } from "../../api/datamanage/fillreport"
import { isEmpty } from "lodash-es"

const auditSituationVisible = ref(false)
const auditSituationType = ref("1")
const auditSituationRow = ref({})
const auditSituationRowId = ref([])
const auditSituationTitle = ref("")

const historyDialogTitle = ref("") // 传递数据给对话框组件
const historyDialogVisible = ref(false) // 控制历史数据抽屉的显示隐藏

const fillreportTreeRef = ref(null)
const defaultExpandedKeys = ref([])
const defaultCurrentNodeKey = ref([])

function handleNodeClick(data) {
  formParam.id = data.id
  getFillreportListFunc()
}

const auditStatusList = ref([
  { label: "草稿", value: "1", color: "color-bg-yellow" },
  { label: "等待审批", value: "2", color: "color-bg-blue" },
  { label: "审批通过", value: "3", color: "color-bg-green" },
  { label: "审批驳回", value: "0", color: "color-bg-red" },
  { label: "作废", value: "4", color: "color-bg-grey" }
])
const formParam = reactive({
  id: "",
  label: "",
  status: "",
  isAlertIndicator: "",
  startUpdated: "", // 新增开始时间
  endUpdated: "", // 新增结束时间
  pageNum: 1,
  pageSize: 10
})
const dataList = ref([])
const multipleSelection = ref([])
const total = ref(0)
const tempDateRange = ref([]) // 新增临时日期范围存储

// 在搜索方法前添加监听
watchEffect(() => {
  if (tempDateRange.value && tempDateRange.value.length === 2) {
    formParam.startUpdated = tempDateRange.value[0] + " 00:00:00"
    formParam.endUpdated = tempDateRange.value[1] + " 23:59:59"
  } else {
    formParam.startUpdated = ""
    formParam.endUpdated = ""
  }
})

function searchWay() {
  formParam.pageNum = 1
  formParam.pageSize = 10
  getFillreportListFunc()
}
const resetForm = () => {
  // formParam.id = defaultCurrentNodeKey.value
  formParam.label = ""
  formParam.status = ""
  formParam.isAlertIndicator = ""
  tempDateRange.value = [] // 重置临时日期范围
  formParam.startUpdated = ""
  formParam.endUpdated = ""
  searchWay()
}

function handleSizeChange(val) {
  formParam.pageSize = val
  getFillreportListFunc()
}
function handleCurrentChange(val) {
  formParam.pageNum = val
  getFillreportListFunc()
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const selectable = (row) => row.status === "1"

const loadNode = async (node, resolve) => {
  // 根节点首次加载
  if (node.level === 0) {
    const { data } = await treeWithLevels()
    // this.processInitialData(data)
    processInitialData(data)

    resolve(data)
    return
  }

  // 后续节点加载
  if (node.level < 4) {
    // 前三级使用预加载数据
    return resolve(node.data.children || [])
  } else {
    // 三级之后动态加载
    const { data } = await nodeLoading(node.data.id)
    if (isEmpty(data)) return resolve([])
    return resolve(data)
  }
}

function processInitialData(data) {
  const keys = []
  const process = (nodes, level) => {
    nodes.forEach((node) => {
      keys.push(node.id)
      node.isLeaf = level === 3 // 第三级标记为非叶子节点
      if (node.children && level < 3) {
        process(node.children, level + 1)
      }
    })
  }

  process(data, 1)
  defaultExpandedKeys.value = keys
  defaultCurrentNodeKey.value = isEmpty(data) ? [] : data[0].id
  formParam.id = data[0].id
  getFillreportListFunc()
}

// 获取指标列表
async function getFillreportListFunc() {
  const { data } = await nodePage(formParam)
  dataList.value = data.records
  total.value = data.total
}

const showHistoryDrawer = ref(false) // 控制历史数据抽屉的显示隐藏

// 批量申请
async function batchApplyFor() {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请先选择要审批申请的数据")
    return
  }

  ElMessageBox.confirm(`请注意是否要审批申请${multipleSelection.value.length}项数据！`, "审批申请", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
    icon: "Warning"
  })
    .then(async () => {
      auditSituationRowId.value = multipleSelection.value.map((i) => i.id)
      await getApplyMetrics()
      auditSituationTitle.value = "指标审批申请"
      auditSituationVisible.value = true // 显示对话框

      auditSituationType.value = "1"
    })
    .catch(() => {})
}

// 批量申请历史
async function batchHistory() {
  historyDialogTitle.value = "审批申请历史" // 传递数据给对话框组件
  historyDialogVisible.value = true // 显示对话框
}

// 保存
async function saveHandle(row) {
  let data = []

  if (row.newIndicatorId && isEmpty(row.newIndicator)) return ElMessage.error("指标名称不能修改为空")
  if (row.newDataTypeId && isEmpty(row.newDataType)) return ElMessage.error("数据源不能修改为空")
  if (row.newCurrentValueId && isEmpty(row.newCurrentValue)) return ElMessage.error("指标不能修改为空")
  if (row.newTargetValueId && isEmpty(row.newTargetValue)) return ElMessage.error("目标不能修改为空")
  if (row.newIsAlertIndicatorId && isEmpty(row.newIsAlertIndicator)) return ElMessage.error("预警指标不能修改为空")

  if (!isEmpty(row.newIndicator)) {
    data.push({
      id: row.newIndicatorId || null,
      metricId: row.id,
      fieldName: "指标名称",
      oldValue: row.indicator,
      newValue: row.newIndicator,
      isAlertIndicator: row.isAlertIndicator
    })
  }
  if (!isEmpty(row.newDataType)) {
    data.push({
      id: row.newDataTypeId || null,
      metricId: row.id,
      fieldName: "数据源",
      oldValue: row.dataType,
      newValue: row.newDataType,
      isAlertIndicator: row.isAlertIndicator
    })
  }
  if (!isEmpty(row.newCurrentValue)) {
    data.push({
      id: row.newCurrentValueId || null,
      metricId: row.id,
      fieldName: "指标修改",
      oldValue: row.currentValue,
      newValue: row.newCurrentValue,
      isAlertIndicator: row.isAlertIndicator
    })
  }
  if (!isEmpty(row.newTargetValue)) {
    data.push({
      id: row.newTargetValueId || null,
      metricId: row.id,
      fieldName: "目标修改",
      oldValue: row.targetValue,
      newValue: row.newTargetValue,
      isAlertIndicator: row.isAlertIndicator
    })
  }
  if (!isEmpty(row.newIsAlertIndicator)) {
    data.push({
      id: row.newIsAlertIndicatorId || null,
      metricId: row.id,
      fieldName: "预警指标",
      oldValue: row.isAlertIndicator,
      newValue: row.newIsAlertIndicator,
      isAlertIndicator: row.isAlertIndicator
    })
  }

  await saveAsDraft(data)
  getFillreportListFunc()

  ElMessage.success("保存成功")
}
// 报批
async function auditHandle(row) {
  auditSituationRowId.value = [row.id]
  await getApplyMetrics()
  auditSituationTitle.value = "指标审批申请"
  auditSituationVisible.value = true // 显示对话框
  auditSituationType.value = "1" // 1:保存 2:报批
}

async function getApplyMetrics() {
  const { data } = await applyMetrics(auditSituationRowId.value)
  auditSituationRow.value = data
}

const showHistoryDrawerId = ref("")
// 历史数据
function historyHandle(row) {
  showHistoryDrawerId.value = row.id
  showHistoryDrawer.value = true
}
// 预览
function previewHandle(row) {}

// 定义格式化时间的方法
const formatDate = (date) => {
  if (date) {
    return dayjs(date).format("YYYY-MM-DD HH:mm:ss")
  }
  return ""
}

// 在 auditStatusList 定义之后添加
const getStatusColor = (status) => {
  const target = auditStatusList.value.find((item) => item.value === status)
  return target?.color || ""
}

const getStatusLabel = (status) => {
  const target = auditStatusList.value.find((item) => item.value === status)
  return target?.label || status
}
// 添加编辑切换方法
const toggleEdit = (row) => {
  if (row.isEditing) {
    // 保存时更新正式值
    row.label = row.editValue
  } else {
    // 进入编辑时暂存原始值
    row.editValue = row.label
  }
  row.isEditing = !row.isEditing
}
</script>
<style scoped lang="scss">
.form-input {
  flex: 1;
}
.editable-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .edit-icon {
    margin-left: 8px;
    cursor: pointer;
    color: #666;
    &:hover {
      color: #0c7cff;
    }
  }
}

::v-deep(.el-tree--highlight-current) {
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #f5f7fa;
    .node-content {
      color: #0c7cff;
      font-weight: 500;
    }
  }
}
.color-bg-yellow {
  background-color: #faad14;
}
.color-bg-green {
  background-color: #52c41a;
}
.color-bg-blue {
  background-color: #0c7cff;
}
.color-bg-red {
  background-color: #ff4d4f;
}
.color-bg-grey {
  background-color: #999999;
}

.statusBox {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  box-sizing: border-box;
  .point {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 5px;
  }
}
.box-flex-row {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  box-sizing: border-box;
  .left1 {
    width: 90px;
    height: 100%;
    display: flex;
  }
  .left2 {
    width: 190px;
    height: 100%;
    display: flex;
  }
}

.box-fillreport {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #f0f0f0;
  padding: 20px 20px 0 20px;
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
  .tree-content {
    width: 320px;
    height: 100%;
    padding: 20px 10px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #e5e6eb;
    overflow: hidden;
    overflow-y: auto;
    box-sizing: border-box;
    .node-content {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      display: block;
    }
  }
  .box-search {
    width: 100%;
    min-height: 40px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    ::v-deep .box-search-left {
      width: auto;
      height: 100%;
      display: flex;
      flex: 1;
      align-items: center;
      box-sizing: border-box;
      .el-range-editor.el-input__wrapper {
        width: 240px !important;
      }
      .el-form-item {
        margin-bottom: 0;
      }
      .el-row {
        line-height: 45px;
      }
      .form-item-responsive .el-form-item__content {
        width: 100%;
        display: flex;
        justify-content: end;
      }
      .el-form--inline .el-form-item {
        display: inline-flex;
        margin-right: 0;
        vertical-align: middle;
        width: 100%;
      }
    }
    .box-search-right {
      width: auto;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: flex-start;
      padding-left: 20px;
      padding-top: 2px;
      box-sizing: border-box;
      ::v-deep .zdy-input {
        width: 264px;
        height: 34px;
        line-height: 34px;
        background: #ffffff;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        margin-right: -2px;
        .el-input__wrapper {
          border-radius: 2px 0 0 2px;
        }
      }
      ::v-deep .zdy-btn {
        width: 56px;
        height: 34px;
        line-height: 34px;
        border-radius: 0;
        border-radius: 0px 2px 2px 0px;
      }
    }
  }
  .box-controller {
    width: calc(100% - 320px);
    height: auto;
    display: flex;
    background-color: #fff;
    padding: 15px 15px 10px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }
  .controller-page {
    width: 100%;
    flex: 1;
    overflow: hidden;
  }
}

.card-table {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
}
.card-total-txt {
  width: 100%;
  height: 20px;
  line-height: 20px;
  font-family:
    Microsoft YaHei,
    Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  text-align: left;
  font-style: normal;
  text-transform: none;
  margin: 9px 0 5px 0;
}
.btn-group-tool {
  width: 100%;
  height: 40px;
  line-height: 40px;
}
.btn-group-notice {
  width: 100%;
  height: 32px;
  line-height: 32px;
  background: #e6f1ff;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #0c7cff;
  padding: 0 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 5px 0;
  .icon {
    width: 16px;
    height: 16px;
    color: #0c7cff;
    margin-right: 5px;
  }
  .txt {
    font-family:
      Microsoft YaHei,
      Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
  .num {
    padding: 0 3px;
    font-family: Helvetica, Helvetica;
    font-weight: bold;
    font-size: 16px;
    color: #0c7cff;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
}

.table-list {
  width: 100%;

  display: flex;
  flex: 1;
  box-sizing: border-box;
  overflow: hidden;
  ::v-deep .el-table {
    .el-table__header-wrapper {
      th {
        background-color: #f5f9fc !important;
        color: #333333;
      }
    }
    .el-table__body-wrapper {
      td {
        color: #333333;
      }
    }
  }
}

.card-pagination {
  width: 100%;
  // height: 36px;
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  box-sizing: border-box;
}
</style>
